package com.cskaoyan.service;

import com.cskaoyan.bean.po.CodePO;
import com.cskaoyan.mapper.CodeMapper;
import com.cskaoyan.util.CodeStringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @param
 * @Date: 2022/6/9 9:56
 * @Description:验证码服务实现类
 * @Author: 李宇浩
 * @return
 */
@Service
public class CodeServiceImpl implements CodeService {

    @Autowired
    CodeMapper codeMapper;

    /**
     * 处理验证码
     */
    @Override
    public void codeHandle(String phone, String code) {
        CodePO codePO = null;
        codePO = codeMapper.selectByPhone(phone);
        // 如果数据库中不存在此申请用户则将此用户和验证码加入数据库
        if (codePO == null) {
            String[] initCodes = CodeStringUtil.init(code);
            CodePO insert = new CodePO();
            insert.setPhone(phone);
            insert.setCode(initCodes);
            codeMapper.insert(insert);
            return;
        }

        // 此时数据库中肯定存在用户，将验证码取出进行整合并放回
        String[] newCodes = CodeStringUtil.addLength(codePO.getCode(), code);
        codePO.setCode(newCodes);
        codeMapper.update(codePO);
    }

    /**
     * 删除过期验证码
     */
    @Override
    public void removeCode(String phone) {
        CodePO codePO = codeMapper.selectByPhone(phone);
        String[] newCode = CodeStringUtil.subLength(codePO.getCode());
        codePO.setCode(newCode);
        codeMapper.update(codePO);
    }

    /**
     * 获取验证码用于校验
     */
    @Override
    public String[] getCode(String phone) {

        CodePO codePO = codeMapper.selectByPhone(phone);

        return codePO.getCode();
    }
}
